package com.travelsky.airchina.boarding.dao;


import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.travelsky.airchina.boarding.domain.Resource;
import com.travelsky.airchina.boarding.domain.User;
/**
 * 用户数据访问
 * @author haichenwang
 *
 */
@Repository("userDAO")
public class UserDAO extends GenericDAOHibernate<User, Long>{
	@Autowired
	public UserDAO(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
	@SuppressWarnings("unchecked")
	public boolean validateUserLoginNameExist(String loginName) {
		String hql = "select count(*) from User where loginName = ? ";
		List<Long> list = this.getHibernateTemplate().find(hql, loginName);
		if(list!=null && list.size()>0){
			if(list.get(0)!=null && list.get(0)>=1){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	@SuppressWarnings("unchecked")
	public User getUser(String loginName) {
		String hql = "from User where loginName = ?";
		List<User> list = this.getHibernateTemplate().find(hql, loginName);
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}
	public boolean isUserLoginNameUnique(String loginName) {
		String hql = "select count(id) from User where loginName = ?";
		int sum = this.countHqlQuery(hql, null);
		return sum>1?false:true;
	}
	@SuppressWarnings("unchecked")
	public List<Resource> findUserOperationResourceList(String loginName) {
		String hql = "select resource_.id,resource_.name,resource_.parentResource.id,resource_.url,resource_.isMenu from Resource resource_ left join resource_.roles roles_ where roles_.id = (select user_.role.id from User user_ where user_.loginName = ?)";
		List<Object[]> list = this.getHibernateTemplate().find(hql,loginName);
		if(list!=null && list.size()>0){
			List<Resource> resources = new ArrayList<Resource>();
			for(Object[] objs:list){
				Resource resource = new Resource();
				resource.setId((Long)objs[0]);
				resource.setName((String)objs[1]);
				if(objs[2]!=null){
					Resource parentResource = new Resource();
					parentResource.setId((Long)objs[2]);
					resource.setParentResource(parentResource);
				}
				resource.setUrl((String)objs[3]);
				resource.setIsMenu((String)objs[4]);
				resources.add(resource);
			}
			return resources;
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public List<Long> findRoleColumnIdListList(String loginName) {
		String hql = "select roleColumn_.columnId from RoleColumn roleColumn_ where roleColumn_.roleId = (select user_.role.id from User user_ where user_.loginName = ?)";
		List<Long> list = this.getHibernateTemplate().find(hql,loginName);
		return list;
	}
	
}
